<template>
  <div class="border">
    <div class="flex-between margin-bottom-10">
      <div class="t-18">
        <span>{{isEdit?'编辑产品':'新增产品'}}</span>
      </div>
      <div>
        <el-button type="primary"
                   @click="saveAll"
                   size="small">提交</el-button>
        <el-button type="danger"
                   @click="handleReset"
                   size="small">重置</el-button>
        <el-button @click="cancelAll"
                   size="small">返回</el-button>
      </div>
    </div>
    <div class="shopEditHead">
      <el-form :model="form"
               :rules="rules"
               ref="form"
               label-width="100px"
               class="demo-ruleForm">
        <el-row>
          <el-col :span="8">
            <el-form-item label="产品类型"
                          prop="type">
              <el-select :multiple="false"
                         v-model="form.type"
                         placeholder="请选择">
                <el-option v-for="item in typeList"
                           :key="item.value"
                           :label="item.label"
                           :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="产品名称"
                          prop="name">
              <el-input v-model="form.name"
                        placeholder="请输入烟弹产品名称"
                        class="input" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="所属系列"
                          prop="series">
              <el-select :multiple="false"
                         v-model="form.series"
                         placeholder="请选择">
                <el-option v-for="item in seriesMap"
                           :key="item.id"
                           :label="item.val"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="8">
            <el-form-item label="最高价(元)"
                          prop="maxPrice">
              <el-input-number v-model="form.maxPrice"
                               :controls="false"
                               :min="0"
                               :max="999999"
                               placeholder="请输入最高价"
                               style="margin-left: 6px"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="最低价(元)"
                          prop="minPrice">
              <el-input-number v-model="form.minPrice"
                               :min="0"
                               :max="999999"
                               :controls="false"
                               placeholder="请输入最低价"
                               style="margin-top: 5px"></el-input-number>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item label="计数单位"
                          prop="unit">
              <el-input v-model="form.unit"
                        placeholder="请输入计数单位"
                        class="input" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="产品特点"
                          prop="productSpecInfoIds">
              <el-select :multiple="true"
                         v-model="form.productSpecInfoIds"
                         placeholder="请选择">
                <el-option v-for="item in productSpecial"
                           :key="item.id"
                           :label="item.val"
                           :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <div class="setLabel">
      <p class="labelItem">
        <span class="textarea">
          <p>产品简介</p>
          <el-input v-model="form.descs"
                    type="textarea"
                    :rows="6"
                    :maxlength="1000"
                    show-word-limit
                    placeholder="请输入产品简介" />
        </span>
      </p>
    </div>
    <!-- 文件上传 -->
    <el-row>
      <el-col :span="8"
              class="padding-right-10">
        <div class="thumbnaimian">
          <el-upload class="upload-demo"
                     :headers="{'Authorization': $store.state.app.token}"
                     action="/file/uploadFile"
                     :limit="1"
                     :on-remove="handlefileRemove"
                     :on-success="handleMainSuccess"
                     :file-list="zhuTuFileList"
                     accept=".jpg, .png, .bmp, .jpeg"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传主图</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传一张jpg/png文件</div>
          </el-upload>
        </div>
      </el-col>
      <el-col :span="8"
              class="padding-right-10">
        <div class="thumbnailLunbo">
          <!-- <span class="imguploadtitle">商品轮播图</span> -->
          <el-upload class="upload-demo"
                     :headers="{'Authorization': $store.state.app.token}"
                     action="/file/uploadFile"
                     :limit="10"
                     :on-remove="handlefileRemove"
                     :on-success="handleCarouseSuccess"
                     :file-list="lunBoTuFileList"
                     accept=".jpg, .png, .bmp, .jpeg"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传轮播图</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传10张jpg/png文件</div>
          </el-upload>
        </div>
      </el-col>
      <el-col :span="8"
              class="padding-right-10">
        <div class="thumbnaimian">
          <el-upload class="upload-demo"
                     :headers="{'Authorization': $store.state.app.token}"
                     action="/file/uploadFile"
                     :limit="10"
                     :on-remove="handlefileRemove"
                     :on-success="handleDetailSuccess"
                     :file-list="detailFileList"
                     accept=".jpg, .png, .bmp, .jpeg"
                     list-type="picture">
            <el-button size="small"
                       type="primary">点击上传详情图片</el-button>
            <div slot="tip"
                 class="el-upload__tip">只能上传10张jpg/png文件</div>
          </el-upload>
        </div>
      </el-col>
    </el-row>
  </div>
</template>
<script>
import { saveProduct, editProduct } from "../../services/product";
import { deleteFile } from '../../services/file'
import { mapState } from 'vuex'

const initDetails = () => {
  return {
    // yanDanProductName: "",
    name: "",
    series: "",
    descs: "",
    type: "",
    minPrice: "",
    maxPrice: "",
    //主图id
    mainImg: "",
    //轮播图ids
    productCarouselImageIds: [],
    //产品详情ids
    productDetailImageIds: [],
    //产品特点ids
    productSpecInfoIds: [],
    unit: "",
  }
}
export default {
  data () {
    return {
      isEdit: false,//是否是编辑
      typeList: [{ value: 2, label: "烟弹", }, { value: 1, label: "烟杆", }], //产品类型
      form: initDetails(), //form表单数据
      // 详情
      rules: {
        name: [{ required: true, message: "请输入产品名", trigger: "blur" }],
        series: [{ required: true, message: "请选择所属系列", trigger: "blur" }],
        type: [{ required: true, message: "请选择产品类型", trigger: "blur" }],
        minPrice: [{ required: true, message: "请输入最低价格", trigger: "blur" }],
        maxPrice: [{ required: true, message: "请输入最高价格", trigger: "blur" }],
        productSpecInfoIds: [{ required: true, message: "请选择产品特点", trigger: "blur" }],
        unit: [{ required: true, message: "请输入产品单位", trigger: "blur" }],
      }, //详情表单规则
      zhuTuFileList: [], //主图文件列表
      lunBoTuFileList: [], //轮播图文件列表
      detailFileList: [],//详情图
    };
  },
  computed: {
    ...mapState('dictionary', ['seriesMap', 'productSpecial']),
    ...mapState('product', ['productDetail'])
  },
  mounted () {
    this.$store.dispatch('dictionary/dispatchProductSpecial') //获取产品特点
    this.isEdit = this.$route.query.isEdit == '0' ? false : true
    if (this.isEdit) {
      this.$nextTick(() => {
        this.getDetail()
      })
    }
  },
  methods: {
    // 获取详情
    getDetail () {
      const { id, mainImgUrl, productCarouselImageUrlList, productDetailImageUrlList, name, series, descs,
        type, minPrice, maxPrice, mainImg, productCarouselImageIds, productDetailImageIds, productSpecInfoIds, unit } = this.productDetail

      this.zhuTuFileList = [{ url: mainImgUrl, response: { data: { id: mainImg } } }]

      this.lunBoTuFileList = productCarouselImageIds.map((item, index) => {
        return { url: productCarouselImageUrlList[index], response: { data: { id: item } } }
      })

      this.detailFileList = productDetailImageIds.map((item, index) => {
        return { url: productDetailImageUrlList[index], response: { data: { id: item } } }
      })

      this.form = {
        id, name, series, descs, type, minPrice, maxPrice, mainImg, productCarouselImageIds, productDetailImageIds, productSpecInfoIds, unit
      }
    },
    // 提交表单
    saveAll () {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          if (!this.isEdit) {
            // 新增
            const res = await saveProduct(this.form)
            if (res.code == 0) {
              this.$message.success('新增成功')
              this.$router.replace('/product')
            } else {
              this.$message.warning(res.msg)
            }
          } else {
            // 编辑
            const res = await editProduct(this.form)
            if (res.code == 0) {
              this.$message.success('更新成功')
              this.$router.replace('/product')
            } else {
              this.$message.warning(res.msg)
            }
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    // 重置表单
    handleReset () {
      this.form = initDetails();
    },
    // 返回上一页
    cancelAll () {
      this.$router.back(-1);
    },
    // 删除主图片
    handlefileRemove (file, fileList) {
      const { id } = file.response.data
      deleteFile(id)
    },
    handleMainSuccess (response, file, fileList) {
      const { id } = response.data
      this.form.mainImg = id
    },
    handleCarouseSuccess (response, file, fileList) {
      const ids = fileList.map(item => {
        return item.response.data.id
      })
      this.form.productCarouselImageIds = ids
    },
    handleDetailSuccess (response, file, fileList) {
      console.log(fileList);
      const ids = fileList.map(item => {
        return item.response.data.id
      })
      this.form.productDetailImageIds = ids
    },
  },
};
</script>
<style lang="scss" scoped>
.border {
  overflow: auto;
  ::v-deep .el-input__inner {
    display: inline-block;
    width: 200px;
  }
  ::v-deep .el-upload-list--picture .el-upload-list__item-thumbnail {
    width: 190px;
  }

  .label {
    width: 150px;
    text-align: right;
    line-height: 40px;
  }
}
</style>
 
 